<?php
class pdfList extends TCPDF
{
    protected static $m_logoW = 566;
    protected static $m_logoH = 86;
    protected static $m_a4width = 595;
    protected static $m_a4height = 841;
    
    protected static $m_tinySize = 10;
    
    protected static $m_smallSize = 12;
    
    protected static $m_mediumSize = 16;
    
    protected static $m_bigSize = 20;
    
//    protected static $m_fontFamily = 'helvetica';
    protected static $m_fontFamily = 'freeserif';
    
    protected static $m_lineStyle = array(
        'width' => 0.1
        , 'cap' => 'butt'
        , 'join' => 'miter'
        , 'dash' => 0
        , 'color' => array(0x00, 0x33, 0x66)
    );
    
    // Quick and dirty solution :)
    const WEB_DIR               = '/home/hipiklt/public_html/';
    
    protected static $m_I18N = null;

    public function Header()
    {
        // Logo
        $this->Image(self::WEB_DIR . 'images/top_pdfui.png', 0, 17, self::$m_logoW, self::$m_logoH, '', '', 'T', '', 1, 'C');
    }


    /**
     * Prepares multi page PDF, containing short information about passed adverts
     *
     * @param array $arObjs of AdvertsMain
     */
    public function prepare($arObjs)
    {
        /* @var $obj Product */

        // Load I18N to use later
        self::$m_I18N = sfContext::getInstance()->getI18N();
        
        // set some language dependent data:
        $lg = Array();
        $lg['a_meta_charset'] = 'UTF-8';
        $lg['a_meta_language'] = 'lt';
        $lg['w_page'] = 'page';

        //set some language-dependent strings
        $this->setLanguageArray($lg);

        sfLoader::loadHelpers('Number');
        sfLoader::loadHelpers('Date');

        $advertSpacing = 10;
        $imageX = 40;
        $textX = 110;
        $startY = self::$m_logoH + 20;
        
        // Reduce A4 width by image size and margin
        $textW = self::$m_a4width - $imageX - $textX - 10;
        
        // Horizontal line after advert
        $lineW = self::$m_a4width - 2 * $imageX;
        
        log_this('Got ' . count($arObjs) . ' adverts to create PDF list');
        
        $onPage = 1;
        $advertY = $startY;

        $this->AddPage();
        foreach( $arObjs as $obj )
        {
            log_this('Adding: ' . $obj->getId() . ' ' . $obj->getCode() . ' ' . $obj->getPrice());
            // Default size
            $imgH = 100;
            $imgW = 0;
            
            // Check if advert will fit on current page
            if( !$this->advertWillFit($onPage, $imgH + $advertSpacing) )
            {
                log_this('Adding new PDF page to fit advert (' . $onPage . ' on page)');
                $this->AddPage('P', 'A4');
                $onPage = 1;
                $advertY = $startY;
            }
            $this->setXY($textX, $advertY);
            $lineY = (int)$advertY + $imgH + $advertSpacing / 2;
            $this->Line($imageX, $lineY, $imageX + $lineW, $lineY, self::$m_lineStyle);
            
            $c = new Criteria();
            $c->add(FilesPeer::OBJ_ID, $obj->getId());
            $c->add(FilesPeer::OBJ_TYPE, MyConstants::TYPE_PRODUCT);
            $photo = FilesPeer::doSelectOne($c);
            //$photo = Files::getByObj($obj->getId(), 1);
            if( !empty($photo) )
            {
            	$this->SetDrawColor(220, 220, 220);
                $img = self::WEB_DIR . 'images/gallery/tiny/' . $photo->getUname();
                log_this('Advert image: ' . $img);
//    
//                // Check for image and display default logo if not
                if( file_exists($img) )
                {
                    log_this("Displaying image at: [$imageX;$advertY] size: $imgW x $imgH");
                    $this->Image($img, $imageX, $advertY, $imgW, $imgH, '', '', '', false, 300, '', false, false, 1);
                }else 
                {
                    log_this('Image ' . $img . ' does not exist!', SF_LOG_WARNING);
                    $this->Image(self::WEB_DIR . 'images/no_photo.jpg', $imageX, $advertY, 0, $imgH);                
                }
            }else 
            {
                log_this('Advert #' . $obj->getId() . ' has no photos!', SF_LOG_WARNING);
                $this->Image(self::WEB_DIR . 'images/gallery/tiny/xxxx.png', $imageX, $advertY, 0, $imgH);                
            }
            
            //$user = User::getById($obj->getUserId());
            $mainInfo = sprintf(
                "%s \n%s"
                , format_currency($obj->getPrice(), $obj->getCurrencyCode())
                //, $obj->getCreatedAt('Y')
                //, $obj->getRealProducerName()
                //, $obj->getCode()
                , $obj->getName()
                
            );
            // Prepare information about advert and owner
            //$str = sprintf("%s\n%s", $this->getAdvertInfo($obj), $this->getUserInfo($user));

            log_this("Cell [$onPage] at: ($textX, $advertY)");
            $this->setXY($textX, $advertY);
//            log_this('Prepare main information: ' . $str);
            $this->SetTextColor(64, 103, 162);
            $this->SetFont(self::$m_fontFamily, 'B', self::$m_mediumSize);
            $this->MultiCell($textW, 20, $mainInfo, 0, 'R');
            
//            log_this('MultiCell [' . $onPage . '] at: (' . $textX . ', ' . $advertY . ')');
//            log_this("MultiCell [$onPage] at: ($textX, " . ($advertY + 20) . ")");
//            $this->setXY($textX, $advertY + 20);
//            log_this('Prepare main information: ' . $str);
//            $this->SetFont(self::$m_fontFamily, '', self::$m_tinySize);
//            $this->SetTextColor(0, 0, 0);
            //$this->MultiCell($textW, $imgH - 20, $str, 0, 'L');
            //$this->MultiCell($textW, $imgH - 20, '---', 0, 'L');

            
            // Next advert will be below
            $advertY += $imgH + $advertSpacing;
         $onPage++;
         log_this('----------------------------------------------------------------');
        }  // END FOREACH ( loop through objects )
        
        
        //$actionName = MyConstants::getActionName($obj->getAction(), sfContext::getInstance()->getUser()->getCulture());
        $filename = sprintf(
            'hipika_%s.pdf'
            , date('Ymd')
        );

        $this->Output(urlencode($filename), 'D');
        
    }
    
    /**
     * Returns whether advert will fit on current A4 PDF page
     *
     * @param integer $onPage number on page (starts from 1)
     * @param integer $imageH height of image to check
     * @return boolean whether advert fits
     */
    protected function advertWillFit($onPage, $imageH)
    {
        // Where upper part of advert will be
        $advertY = $onPage * $imageH + self::$m_logoH + 30;
        log_this("Check if upper advert Y [$advertY] fits to A4 height (w/o footer) " . (self::$m_a4height - 50));
        return $advertY < self::$m_a4height - 50;
    }
    

    // Page footer
    public function Footer()
    {
        $w = self::$m_logoW;
        $h = 24;
        $y = self::$m_a4height - $h - 6;
        // Logo
        $this->Image(self::WEB_DIR . 'images/bottom_pdfui.png', 0, $y, $w, $h, '', '', 'B', '', 1, 'C');
        // Position from bottom
        $this->SetXY(0, -30);
        // Set font
        $this->SetFont(self::$m_fontFamily, '', self::$m_tinySize);
        //$this->SetFillColor(64, 103, 162);
        // Page number
        $this->Cell(self::$m_a4width, 25, 'Page ' . $this->getAliasNumPage() . '/' . $this->getAliasNbPages(), 0, 0, 'C', 0);
    }
}
?>
